//
//  UserAccount.swift
//  sinazd
//
//  Created by apple on 16/3/8.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

import AFNetworking


private let userInfoKey = "cn.itcast.account"



class UserAccount: NSObject {
    
    //创建一个单例
    static let sharedAccount = UserAccount()
    
    //定义一个属性来标识当前token是否为空
    var userLogin: Bool {
        
        return access_token != nil
        
    }
    
    
    
    //用来调用接口授权后的access_token
    var access_token: String?
    
    // access_token的生命周期，单位是秒
    var expires_in: NSTimeInterval = 0 {
        
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    
    
    
    //当前授权用户的uid
    var uid: String?
    
    //好友显示名称
    var name: String?
    
    //用户头像地址(大图)  180x180像素
    var avatar_large: String? {
        
        didSet {
            
            headImageURL = NSURL(string: avatar_large ?? "")
            
        }
        
    }
    
    var headImageURL: NSURL?
    
    //token的过期时间
    var expires_date: NSDate?
    
    
    
    //使用kvc设置属性的初始值
    override private init() {
        
        super.init()
        self.loadUserInfo()
        
    }
    
    //字典里没有的属性，赋值时不进行操作
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //重写descriptiong 属性
    override var description: String {
        
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        
        let dict = self.dictionaryWithValuesForKeys(keys)
        
        return dict.description
        
    }
    
    
}

//保存数据  获取数据
extension UserAccount {
    
    //保存用户信息
    func saveUserInfo(dict: [String : AnyObject]) {
        
        //给当前对象kvc设置初始值 - 未登录状态-》登录状态
        //这个dict是传过来的，实现kvc赋值 可以通过self.（self的一个属性）取值
        self.setValuesForKeysWithDictionary(dict)
        
        //保存self的所有属性 用字典的形式
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        
        
        //通过这个方法，可以给字典里的key 赋值。  赋值过程为 keys["access_token"] = self.access_token 而这个self.access_token 可以取值， 是通过上面的kvc赋值实现的
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        
        userDefaults.synchronize()
    }
    
    
    //提供对外访问保存信息的方法
    func loadUserInfo() {
        
        //从偏好设置获取字典信息
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            
            return
        }
        
        // 通过字典信息 把自己的属性 转换成模型数据
        self.setValuesForKeysWithDictionary(dict)
        
        //token过期，则把当前用户信息重置为未登录。所以定义一个属性，来返回 过期日期和当前日期 的比较值
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            
            
        }else{
            
            self.access_token = nil
            
        }
        
    }
    
    //获取token
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
        
        let urlString = "oauth2/access_token"
        
        let parameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        
        HTTPClient.sharedHTTPClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                
                finished(isSuccess: false)
                return
            }
            
            self.loadUserInfo(dict!, finished: finished)
            
        }
        
    }
    
    
    
    //获取用户信息
    private func loadUserInfo(dicts: [String : AnyObject],finished:(isSuccess:Bool)->()) {
        
        let token = dicts["access_token"] as! String
        
        let uid = dicts["uid"] as! String
        
        let urlStr = "2/users/show.json"
        
        let parameters = ["access_token":token,"uid":uid]
        
        
        
        HTTPClient.sharedHTTPClient.requestJSONDict(.GET, urlString: urlStr, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                
                finished(isSuccess: false)
                return
                
            }
            
            guard var userInfoDict = dict else {
                
                finished(isSuccess: false)
                return
            }
            
            for (k,v) in dicts {
                
                userInfoDict[k] = v
                
            }
            

            
            self.saveUserInfo(userInfoDict)
            
            finished(isSuccess: true)
            
        }
        
    }
    
}




